package com.lepu.app.main.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View.OnClickListener;

import com.app.config.AppConfig;
import com.app.utils.Const;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.ConnectivityReceiver;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.CrashHandler;
import com.core.lib.utils.main.FileUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;

public class MainActivityBase extends BaseFragmentActivity implements
        CrashHandler.CrashHandlerListener, ConnectivityReceiver.OnNetworkAvailableListener {

    private long mExitTime = 0;
    private ConnectivityReceiver mConnectivityReceiver = null;

    /**
     * 主程序中的自动升级，等配置，抽象到外层。
     */
    @SuppressLint("ResourceAsColor")
    @Override
    public void onCreate(Bundle savedInstanceState) {

        mNeedSwipeBack = false;
        super.onCreate(savedInstanceState);

        //注册自定义广播
        registerAppReceiver();

        // 初始化自定义异常
        if(Setting.NeedCrashLog)
        {
        	CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(getApplicationContext(), this);
        }

        // 提示用户有未提交服务器的异常
        //doWithCacheException();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegisterAppReceiver();
    }

    @Override
    public void onBackPressed() {
        //backFinishCheck();

        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            UIHelper.showToast(this, "再按一次退出程序");
            mExitTime = System.currentTimeMillis();
        } else {
            AppManager.getAppManager().AppExit(MainActivityBase.this);
        }
    }

    private void registerAppReceiver() {
        mConnectivityReceiver = new ConnectivityReceiver(this);
        mConnectivityReceiver.setOnNetworkAvailableListener(this);
        mConnectivityReceiver.bind(this);
    }

    private void unRegisterAppReceiver() {
        mConnectivityReceiver.unbind(this);
    }

    /*
     * 处理缓存到本地的最后一次异常
     */
    @SuppressWarnings("unused")
    private void doWithCacheException() {
        boolean hasException = AppConfig.getConfigBoolean(this,
                Const.CONFIG_APP_EXCEPTION_IF, false);
        if (hasException) {
            String exceptionString = AppConfig.getConfigString(this,
                    Const.CONFIG_APP_EXCEPTION_VALUE, "");
            if (!StringUtilBase.stringIsEmpty(exceptionString)) {
                CrashHandler instance = CrashHandler.getInstance();
                if (instance != null) {
                    instance.sendMessageToServer(exceptionString, this, true);
                }
            }
        }
    }

//    @SuppressWarnings("unused")
//    private void backFinishCheck() {
//        MyDialog dialog = new MyDialog(this)
//                .setMessage(R.string.app_quit_message)
//                .setPositiveButton(R.string.app_ok, new View.OnClickListener() {
//
//                    @Override
//                    public void onClick(View v) {
//                        AppManager.getAppManager().AppExit(MainActivityBase.this);
//                    }
//                })
//                .setNegativeButton(R.string.app_cancel, new View.OnClickListener() {
//
//                    @Override
//                    public void onClick(View v) {
//                    }
//                });
//
//        dialog.create(null);
//        dialog.showMyDialog();
//    }

    // =====================自定义异常处理，抓取log传入自己的服务器中============================================================
    @Override
    public int getToastStringId() {
        return R.string.exception_toast_user;
    }

    @Override
    public void setException(boolean hasException, String exceptionString) {
        // 设置最后一次异常缓存到本地，
        AppConfig.setConfig(this, Const.CONFIG_APP_EXCEPTION_IF, hasException);
        AppConfig.setConfig(this, Const.CONFIG_APP_EXCEPTION_VALUE, exceptionString);

        //保存到本地
        String path = SdLocal.getTempFilePath(this, "crash_" + System.currentTimeMillis());
        FileUtilBase.saveFile(path, exceptionString.getBytes(), false);

        //传到umeng
        UmengHelper.reportError(this, exceptionString);

        //no use
        //AppManager.getAppManager().AppExit(this);
    }

    @Override
    public void showExceptionDialog(OnClickListener okClick,
                                    OnClickListener cancelClick) {
        if (!this.isFinishing()) {
            // show dialog
            new MyDialog(this)
                    .setMessage(R.string.exception_message_desc)
                    .setPositiveButton(R.string.exception_ok, okClick)
                    .setNegativeButton(R.string.exception_cancel, cancelClick)
                    .create(cancelClick).show();
        }
    }

    @Override
    public String getUploadLogUrl() {
        return Setting.getUploadLogUrl();
    }

    @Override
    public void onNetworkAvailable() {
        LogUtilBase.LogD(null, "change 网络可用");
        MainTabActivity.getInstance().startChat();
    }

    @Override
    public void onNetworkUnavailable() {
        LogUtilBase.LogD(null, "change 网络不可用");
    }
}
